package wsz.consumer.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

/**
 * @author wsz
 * @date 2021/11/30 18:18
 **/
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable {

    private ChannelHandlerContext context;
    private String requestMsg;
    private String responseMsg;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
        System.out.println("通道已建立");
    }

    @Override
    protected synchronized void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        responseMsg = msg;
        // 唤醒等待的线程
        notify();
    }

    @Override
    public synchronized Object call() throws Exception {
        context.writeAndFlush(requestMsg);
        wait();
        return responseMsg;
    }


    public void setRequestMsg(String requestMsg) {
        this.requestMsg = requestMsg;
    }

}
